package com.ruike.alisurface.ui.payPage;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.SystemClock;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ruike.alisurface.BuildConfig;
import com.ruike.alisurface.MyApplication;
import com.ruike.alisurface.R;
import com.ruike.alisurface.Serials.MsgEventBus;
import com.ruike.alisurface.base.BaseAty;
import com.ruike.alisurface.bean.CarGoodsBeans;
import com.ruike.alisurface.bean.CardTopUpBean;
import com.ruike.alisurface.bean.CreateOrderResultBean;
import com.ruike.alisurface.bean.ShopDetailBean;
import com.ruike.alisurface.http.MchApiHttp;
import com.ruike.alisurface.ui.dialog.CustomDialog;
import com.ruike.alisurface.utils.BackMainUtils;
import com.ruike.alisurface.utils.MyCountDownTimer;
import com.ruike.alisurface.utils.ShareKey;
import com.ruike.alisurface.utils.ZXingUtils;
import com.voodoo.lib_utils.GsonUtils;
import com.voodoo.lib_utils.L;
import com.voodoo.lib_utils.ShareUtils;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Author: voodoo
 * CreateDate: 2020-04-08
 * Description: 聚合扫码支付
 */
public class PayForPolymerizationActivity extends BaseAty {

    @BindView(R.id.titleBar_titleIco_imgv)
    ImageView titleBarTitleIcoImgv;
    @BindView(R.id.titleBar_appVersion_tv)
    TextView titleBarAppVersionTv;
    @BindView(R.id.titleBar_sn_tv)
    TextView titleBarSnTv;
    @BindView(R.id.titleBar_setting_view)
    View titleBarSettingView;
    @BindView(R.id.titleBar_root_rlayout)
    RelativeLayout titleBarRootRlayout;

    @BindView(R.id.alchatPay_goback_imgv)
    ImageView alchatPayGobackImgv;
    @BindView(R.id.alchat_tuijian)
    TextView alchatTuijian;
    @BindView(R.id.alchat_zxing_code)
    ImageView alchatZxingCode;
    @BindView(R.id.alchat_zxing_price)
    TextView aliZxingPrice;
    @BindView(R.id.alchat_zxing_count_time)
    TextView aliZxingCountTime;

    String OrderNO;
    Bitmap bitmap;
    Timer paytimer;
    TimerTask timerTask;

    @BindView(R.id.pay_type_yhmj)
    TextView payTypeYhmj;
    @BindView(R.id.pay_type_yhljm)
    TextView payTypeYhljm;
    @BindView(R.id.pay_type_mjyh)
    RelativeLayout payTypeMjyh;
    @BindView(R.id.pay_type_zklv)
    TextView payTypeZklv;
    @BindView(R.id.pay_type_zkyh)
    RelativeLayout payTypeZkyh;
    @BindView(R.id.alchat_yj)
    TextView alchatYj;
    @BindView(R.id.alchat_yyhje)
    TextView alchatYyhje;
    @BindView(R.id.alchat_yyh_payje)
    TextView alchatYyhPayje;
    @BindView(R.id.pay_type_moryh)
    RelativeLayout payTypeMoryh;
    @BindView(R.id.layout_yhhd)
    LinearLayout layoutYhhd;

    @BindView(R.id.view_zw_hdie)
    View vhide;

    // 卡充值扫码
    private boolean isTopCarPay = false;
    private CardTopUpBean cardTopUpBean;// 创建卡充值回传对象
    List<CarGoodsBeans> paycarlist;//购物车集合
    double monry = 0.0f;//总金额
    CreateOrderResultBean orderBean;//订单类
    ShopDetailBean shopDetailBean;//商品详情类
    CustomDialog dialog;//弹窗
    AlertDialog alertDialog;//提示框

    @Override
    protected boolean getCanToOtherApp() {
        return false;
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_pay_polymerization;
    }

    @Override
    protected void initViews() {
        L.i("扫码支付页==" + this.getClass().getName());
        initTitleBar(false);

    }


    @Override
    protected void initData() {

        // 20200703 卡充值的时候传入数据，直接处理卡充值的数据
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            isTopCarPay = bundle.getBoolean("isTopCarPay", true);
            cardTopUpBean = (CardTopUpBean) bundle.getSerializable("cardTopUpBean");
            OrderNO = cardTopUpBean.getData().getOrder().getOrderNo();
            aliZxingPrice.setText(new StringBuffer("总金额：").append(cardTopUpBean.getData().getOrder().getTotal_fee()).toString());
            bitmap = ZXingUtils.getInstance().createQRImage((cardTopUpBean.getData().getUrl()), 500, 500, BitmapFactory.decodeResource(getResources(), 0));
            alchatZxingCode.setImageBitmap(bitmap);

            if (timerTask != null) {
                timerTask.cancel();
            }
            if (!BuildConfig.DEBUG) {
                timerTask = new TimerTask() {
                    @Override
                    public void run() {
                        MchApiHttp.getPayResult(PayForPolymerizationActivity.this, OrderNO);
                    }
                };
                paytimer.schedule(timerTask, 10, 3000);
            } else {
                new MyCountDownTimer(5000, 5000) {

                    @Override
                    public void onTick(long millisUntilFinished) {

                    }

                    @Override
                    public void onFinish() {
                        Bundle bundle = new Bundle();
                        bundle.putString("resultStr", new StringBuffer("充值成功\n\n\r").append("卡：123456789 在机器：qwertyuiop 上充值了好几兆亿，但是是假的，惊不惊喜，意不意外，开不开森 (→o→)").toString());
                        startActivity(TopUpResultActivity.class, bundle);
                    }
                }.start();
            }
            return;
        }

        paycarlist = MyApplication.finalDbUtils.findAll(CarGoodsBeans.class);
        SystemClock.sleep(500);
        if (paycarlist == null) {
            L.i("查询商品数据异常");
            return;
        }
        showcodeAlt();
    }

    @Override
    protected void onResume() {
        super.onResume();
        startCountdownTimer(300, aliZxingCountTime, isTopCarPay ? null : SelectPayTypeActivity.class);
    }

    @Override
    public void onSuccess(String requestUrl, String requestJsonStr) {
        super.onSuccess(requestUrl, requestJsonStr);
        L.i("requestUrl==" + requestUrl);
        if (requestUrl.endsWith("CreateSlotOrder") || requestUrl.endsWith("CreateProductOrder")) {
            // 获取商品支付信息
            orderBean = GsonUtils.json2Model(requestJsonStr, CreateOrderResultBean.class);

            CreateOrderResultBean.DataBean dataBean = orderBean.getData();
            String zxinurl = dataBean.getUrl();
            OrderNO = dataBean.getId();
            bitmap = ZXingUtils.getInstance().createQRImage((zxinurl), 500, 500, BitmapFactory.decodeResource(getResources(), 0));
            if (alertDialog != null && alertDialog.isShowing()) {
                alertDialog.dismiss();
            }
            alchatZxingCode.setImageBitmap(bitmap);

            shopDetailBean = new ShopDetailBean(OrderNO);
            shopDetailBean.setTotal_fee(dataBean.getTotal_fee());
            shopDetailBean.setPay_fee(dataBean.getTotal_fee());

            List<ShopDetailBean.OrderDetailsBean> detailOrderList = new ArrayList<>();
            for (CreateOrderResultBean.DataBean.DetailsBean detailsBean : dataBean.getDetails()) {
                ShopDetailBean.OrderDetailsBean orderDetailsBean = new ShopDetailBean.OrderDetailsBean();
                orderDetailsBean.setQuantity(detailsBean.getQuantity());
                orderDetailsBean.setSlotIndex(detailsBean.getSlotIndex());
                orderDetailsBean.setSlotTypeId(detailsBean.getSlotTypeId());
                orderDetailsBean.setPrice(detailsBean.getPrice());
                detailOrderList.add(orderDetailsBean);
            }
            shopDetailBean.setDetailOrderList(detailOrderList);
            L.i("shopDetailBean", shopDetailBean.toString());
            setCanal();
            monry = dataBean.getTotal_fee();
            paytimer = new Timer();
            timerTask = new TimerTask() {
                @Override
                public void run() {
                    MchApiHttp.getPayResult(PayForPolymerizationActivity.this, OrderNO);
                }
            };
            paytimer.schedule(timerTask, 10, 3000);

            aliZxingPrice.setText(new StringBuffer("总金额：").append(monry).toString());


        } else if (requestUrl.endsWith("getPayResult")) {
            JSONObject object = null;
            try {
                object = new JSONObject(requestJsonStr);
                int code = object.optInt("code");
                L.i("getPayResult==" + requestJsonStr);
                if (code == 0) {
                    setCanal();
                    if (isTopCarPay) {
                        Bundle bundle = new Bundle();
                        bundle.putString("resultStr", new StringBuffer("充值成功\n\r").append(cardTopUpBean.getData().getOrder().getDetails()).toString());
                        startActivity(TopUpResultActivity.class, bundle);
                    } else {
                        String order_code = ShareUtils.getInstance().getString(ShareKey.ORDER_RESULT, "");
                        L.iTag("支付页==order_code= ", "上次的单号==" + order_code + "==");
                        if (!TextUtils.isEmpty(order_code) && shopDetailBean != null && order_code.equals(shopDetailBean.getOrderId())) {
                            L.iTag("支付页==order_code= ", "这次的单号=="
                                    + shopDetailBean.getOrderId() + "==" + "多次出 货，订单号已经出货过 无法再次出货 回到主页面");
                            BackMainUtils.setActivity(this);
                            finish();
                            return;
                        }
                        Bundle bundle = new Bundle();
                        bundle.putString("pay_type", "wechat");
                        bundle.putSerializable("orderBeanData", shopDetailBean);
                        startActivity(PayShowShopActivity.class, bundle);
                        finish();
                    }
                } else {
                    L.i("getPayResult" + "==等待支付=");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onError(String requestUrl, String errorMsg) {
        super.onError(requestUrl, errorMsg);
        if (requestUrl.endsWith("getPayResult")) {
            L.e(requestUrl + "==onError=" + errorMsg, "---等待支付--");
//            setCanal();
//            Bundle bundle = new Bundle();
//            bundle.putString("pay_type", "wechat");
//            bundle.putSerializable("orderBeanData", shopDetailBean);
//            startActivity(PayShowShopActivity.class, bundle);
//            finish();
        } else if (requestUrl.endsWith("CreateSlotOrder") || requestUrl.endsWith("CreateProductOrder")) {
            if (alertDialog != null && alertDialog.isShowing()) {
                alertDialog.dismiss();
            }
            L.e(requestUrl + "=onError==" + errorMsg);
            showErrorTip(errorMsg);
        }
    }

    @OnClick({R.id.alchatPay_goback_imgv})
    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.alchatPay_goback_imgv:
                String tip = "支付过程中请勿关闭该扫码支付页面，否则即使支付成功也无法出货！！！\r\n\r\n" +
                        "如想返回其它页面则点击确认，否则点击取消等待支付完成后出货！！！";
                gobackTip(tip, SelectPayTypeActivity.class);
                break;
        }
    }


    public void gobackTip(String tip, Class<?> cls) {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
        dialog = new CustomDialog.Builder(this).setTitle("温馨提示")
                .setMessage(tip).setTouchOutsideCloseDialog(false)
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        sendOrderStatus(0);
                        if (isTopCarPay) {
                            startCountdownTimer(0, null, null);
                        } else {
                            startActivity(cls, null);
                            finish();
                        }

                    }
                }).setNegativeButton("取消", null).create();
        dialog.show();
    }


    /**
     * 生成二维码提示框
     */
    private void showcodeAlt() {
        try {
            showProgressDialog("正在生成二维码加载数据，请稍后......", false);
            MchApiHttp.postCreateQRCodeOrder(this, paycarlist);
        } catch (Exception e) {
            L.i("pay====error==", e.getLocalizedMessage());
        }
    }

    public void setCanal() {
        if (timerTask != null) {
            L.i("==setCanal=取消计时=timerTask=" + timerTask);
            timerTask.cancel();
            timerTask = null;
        }
        if (paytimer != null) {
            L.i("==setCanal=取消计时=paytimer" + paytimer);
            paytimer.cancel();
            paytimer = null;
        }


    }


    @Override
    public void doEventBusResult(MsgEventBus event) {
        if (event.getType().equals("计时结束") && event.getMessage().equals("查询订单倒计时结束")) {
//                EventBus.getDefault().post(new MsgEventBus("计时结束", "查询订单倒计时结束"));
            sendOrderStatus(1);

        }

    }

    /**
     * 上传订单是否超时
     */
    public void sendOrderStatus(int sign_order_state) {
        if (!TextUtils.isEmpty(OrderNO)) {
            MchApiHttp.sendSign_order(OrderNO, sign_order_state, PayForPolymerizationActivity.this);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        L.i("==onDestroy==");
        if (dialog != null && dialog.isShowing()) {
            dialog.cancel();
            dialog = null;
        }
        MchApiHttp.cancalpayResult();
        setCanal();

        if (bitmap != null) {

            alchatZxingCode.setImageBitmap(null);
            bitmap.recycle();
            bitmap = null;
        }

        if (alertDialog != null) {
            alertDialog.dismiss();
            alertDialog = null;
        }
    }


}
